<!--
/**
* Copyright (C) 2022-2023 Timber Chain Cloud (TimberCLD). All Rights Reserved.
* 
* @author: luoweijian
* @email: 807301075@qq..com
* @site: https://www.timbercld.com/
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
*  limitations under the License.
*/
-->
<template>
  <el-dialog v-model="options.visible" :title="!formData.id ? t('add') : t('update')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form v-loading="options.loading" :model="formData" :rules="formRules" ref="formRef" @keyup.enter="submitDataFormHandle()" label-width="120px">
      <el-form-item prop="type" :label="t('menu.type')" size="small">
        <el-radio-group v-model="formData.type" :disabled="!!formData.id">
          <el-radio :label="0">{{ t('menu.type0') }}</el-radio>
          <el-radio :label="1">{{ t('menu.type1') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="name" :label="t('menu.name')">
        <el-input v-model="formData.name" :placeholder="t('menu.name')"></el-input>
      </el-form-item>
      <el-form-item prop="parentName" :label="t('menu.parentName')" class="menu-list">
        <el-popover placement="bottom-start" trigger="click" ref="menuListPopover" :virtual-ref="menuListPopoverBtn" virtual-triggering width="auto">
          <el-tree
            :data="menuList"
            :props="defaultProps"
            node-key="id"
            ref="menuListTreeRef"
            :highlight-current="true"
            :expand-on-click-node="false"
            accordion
            @current-change="menuListTreeCurrentChangeHandle"
          >
          </el-tree>
        </el-popover>
        <el-input v-model="formData.parentName" ref="menuListPopoverBtn" :readonly="true" :placeholder="t('menu.parentName')">
          <template #suffix v-if="formData.pid !== '0'">
            <el-icon @click.stop="deptListTreeSetDefaultHandle()"><CircleClose /></el-icon>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item v-if="formData.type === 0" prop="url" :label="t('menu.url')">
        <el-input v-model="formData.url" :placeholder="t('menu.url')"></el-input>
      </el-form-item>
      <el-form-item prop="order" :label="t('menu.order')">
        <el-input-number v-model="formData.order" controls-position="right" :min="0" :label="t('menu.order')"></el-input-number>
      </el-form-item>
      <el-form-item prop="permissions" :label="t('menu.permissions')">
        <el-input v-model="formData.permissions" :placeholder="t('menu.permissionsTips')"></el-input>
      </el-form-item>
      <el-form-item v-if="formData.type === 0" prop="icon" :label="t('menu.icon')" class="icon-list">
        <tcc-icon-picker v-model="formData.icon" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="options.visible = false">{{ t('cancel') }}</el-button>
      <el-button type="primary" @click="submitDataFormHandle">{{ t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { ResType } from '@/utils/request';
import { ref, reactive, nextTick, watch } from 'vue';
import debounce from 'lodash/debounce';
import type { ElForm, ElTree } from 'element-plus';
import TccIconPicker from '@/components/tcc-icon-picker/tcc-icon-picker.vue';
import { ElMessage, FormRules } from 'element-plus';
import { systemApi } from '@/api/system';
// #region 类型
type MenuValue = {
  id: string;
  name: string;
};
type FormData = {
  id: string;
  type: number;
  name: string;
  pid: string;
  parentName: string;
  url: string;
  permissions: string;
  order: number;
  icon: string;
};
// #endregion

// #region 属性
const emit = defineEmits<{
  refreshPageHandle: [];
}>();

const formRef = ref<InstanceType<typeof ElForm> | null>(null);
const menuListTreeRef = ref<InstanceType<typeof ElTree> | null>(null);

const menuListPopoverBtn = ref() as any;
const menuListPopover = ref() as any;

const { t } = useI18n();
const dialogId = ref('');

// 页面配置
const options = reactive({
  loading: false,
  visible: false,
});
// 表单数据
const formData = reactive<FormData>({
  id: '',
  type: 0,
  name: '',
  pid: '0',
  parentName: '',
  url: '',
  permissions: '',
  order: 0,
  icon: '',
});
// 菜单数据
const menuList = ref([]);
const defaultProps = ref({ label: 'name', children: 'children' });
// 校验规则
const formRules = reactive<FormRules<FormData>>({
  name: [{ required: true, message: t('validate.required'), trigger: 'blur' }],
  parentName: [{ required: true, message: t('validate.required'), trigger: 'change' }],
});

// #endregion

// #region 方法
watch([() => formData.type, () => dialogId.value], (val1) => {
  formRef.value?.clearValidate();
  formData.id = val1[1];
});

// 获取菜单列表
const getMenuList = async () => {
  systemApi.getMenuList().then((res) => {
    if (res?.code === 0) {
      Object.assign(menuList.value, res.data);
    } else {
      ElMessage.error(res.msg);
    }
  });
};
// 上级菜单树, 设置默认值
const deptListTreeSetDefaultHandle = () => {
  formData.pid = '0';
  formData.parentName = t('menu.parentNameDefault');
};
// 上级菜单树, 选中
const menuListTreeCurrentChangeHandle = async (data: MenuValue) => {
  formData.pid = data.id;
  formData.parentName = data.name;
};
// 获取菜单信息
const getMenuInfo = async () => {
  systemApi.getMenuInfo(formData.id).then(async (res) => {
    if (res?.code === 0) {
      await nextTick();
      Object.assign(formData, res.data);
      if (formData.pid === '0') {
        return deptListTreeSetDefaultHandle();
      }
      menuListTreeRef.value?.setCurrentKey(formData.pid);
    }
  });
};

const init = async () => {
  options.loading = true;
  options.visible = true;
  await nextTick();
  formRef.value?.resetFields();
  formData.parentName = t('menu.parentNameDefault');
  await Promise.all([getMenuList()]).then(() => {
    if (formData.id) {
      getMenuInfo();
    }
  });
  setTimeout(() => {
    options.loading = false;
  }, 500);
};

// 新增菜单
function insertMenu() {
  return new Promise<ResType<unknown>>((resolve, reject) => {
    systemApi
      .insertMenu(formData)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => [reject(err)]);
  });
}
// 更新菜单
function updateMenu() {
  return new Promise<ResType<unknown>>((resolve, reject) => {
    systemApi
      .updateMenu(formData)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => [reject(err)]);
  });
}

// 表单提交
function submit() {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      options.loading = true;
      if (!formData.icon) {
        formData.icon = 'Document';
      }
      let res;
      if (formData.id) {
        res = await updateMenu();
      } else {
        res = await insertMenu();
      }
      if (res?.code !== 0) {
        ElMessage.error(res.msg);
      } else {
        ElMessage.success(t('prompt.success'));
        options.visible = false;
        emit('refreshPageHandle');
      }
    }
  });
}
// 防抖
const submitDataFormHandle = debounce(submit, 1000, { leading: true, trailing: false });

defineExpose({
  init,
  dialogId,
});
// #endregion
</script>

<style lang="scss">
.system__menu {
  .menu-list,
  .icon-list {
    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }
  &-icon-popover {
    width: 458px;
    overflow: hidden;
  }
  &-icon-inner {
    width: 478px;
    max-height: 258px;
    overflow-x: hidden;
    overflow-y: auto;
  }
  &-icon-list {
    width: 458px;
    padding: 0;
    margin: -8px 0 0 -8px;
    > .el-button {
      padding: 8px;
      margin: 8px 0 0 8px;
      > span {
        display: inline-block;
        vertical-align: middle;
        width: 18px;
        height: 18px;
        font-size: 18px;
      }
    }
  }
}
.el-input__suffix-inner {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
